﻿using Framework;
using Framework.Models;
using Koala.Framework;
using Koala.JiraTool.TaskList.Dialog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Koala.JiraTool.TaskList
{
    public partial class TaskListControl : UserControl, ITransientDependency
    {
        #region Field

        private readonly List<TaskInfo> _taskInfos = new List<TaskInfo>();
        private readonly IContainer _container;
        private readonly IDataPersistence _dataPersistence;
        private readonly GlobalSettings _globalSettings;
        private readonly ITokenController _tokenController;
        private string[] _taskStatus;

        #endregion Field

        #region Constructor

        public TaskListControl()
            : this(null, null, null, null)
        {
        }

        public TaskListControl(IContainer container, IDataPersistence dataPersistence, GlobalSettings globalSettings, ITokenController tokenController)
        {
            _container = container;
            _dataPersistence = dataPersistence;
            _globalSettings = globalSettings;
            _tokenController = tokenController;
            InitializeComponent();
            dgvMain.AutoGenerateColumns = false;
        }

        #endregion Constructor

        #region Event

        private void TaskListControl_Load(object sender, EventArgs e)
        {
            if (DesignMode)
                return;
            var list = _dataPersistence.Get<List<TaskInfo>>(Name + "_TaskList");
            _taskInfos.Clear();
            if (list == null) return;
            _taskInfos.AddRange(list);
            DataBind();
        }

        private void tsbAdd_Click(object sender, EventArgs e)
        {
            var addTaskDialog = _container.Resolve<AddTaskDialog>();
            addTaskDialog.Name = Name + "_AddTaskDialog";
            addTaskDialog.LoadControl(_taskStatus);
            var result = addTaskDialog.ShowDialog();
            if (result != DialogResult.OK)
                return;
            var sList = addTaskDialog.GetList();
            var addList = sList.Where(model => _taskInfos.All(m => m.Keyword != model.Keyword));
            _taskInfos.AddRange(addList);
            DataBind();
        }

        private void tsbDel_Click(object sender, EventArgs e)
        {
            var rows = dgvMain.SelectedRows;
            if (rows.Count == 0)
                return;
            foreach (DataGridViewRow row in rows)
            {
                var keyword = row.Cells["Keyword"].Value.ToString();
                var model = _taskInfos.First(m => m.Keyword == keyword);
                _taskInfos.Remove(model);
            }
            DataBind();
        }

        private void tsbResolveTask_Click(object sender, EventArgs e)
        {
            var rows = dgvMain.SelectedRows;
            if (rows.Count == 0)
                return;
            if (rows.Count > 1)
            {
                MessageBox.Show("只能选择一项进行操作。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var row = rows[0];
            var keyword = row.Cells["Keyword"].Value.ToString();
            var model = _taskInfos.First(m => m.Keyword == keyword);
            if (model == null)
            {
                MessageBox.Show("数据异常无法进行该操作。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var form = _container.Resolve<ResolveTaskDialog>();
            form.LoadDialog(model);
            form.ShowDialog();
        }

        private void tsmiOpenDetailed_Click(object sender, EventArgs e)
        {
            OpenUrl(task => string.Format(_globalSettings.TaskViewUrlFormat, task.Keyword));
        }

        private void tsmiOpenResolve_Click(object sender, EventArgs e)
        {
            OpenUrl(task => string.Format("{0}secure/CommentAssignIssue!default.jspa?id={1}&action=5", _globalSettings.RootUrl, task.Id));
        }

        #endregion Event

        #region Public Method

        public void SetTaskStatus(params string[] taskStatus)
        {
            _taskStatus = taskStatus;
        }

        public List<TaskInfo> GetList()
        {
            return _taskInfos;
        }

        public List<TaskInfo> GetSelectList()
        {
            var list = new List<TaskInfo>();
            var rows = dgvMain.SelectedRows;
            if (rows.Count == 0)
                return list;
            foreach (DataGridViewRow row in rows)
            {
                var keyword = row.Cells["Keyword"].Value.ToString();
                var model = _taskInfos.First(m => m.Keyword == keyword);
                list.Add(model);
            }
            return list;
        }

        public void SetDataGridView(List<TaskInfo> taskInfos)
        {
            foreach (var taskInfo in taskInfos)
            {
                var model = _taskInfos.FirstOrDefault(m => m.Id == taskInfo.Id);
                if (model == null)
                    return;
                model.Status = taskInfo.Status;
            }
            DataBind();
        }

        public void SetControl(bool readOnly)
        {
            dgvMain.Enabled = toolStrip.Enabled = readOnly;
        }

        #endregion Public Method

        #region Private Method

        private void DataBind()
        {
            dgvMain.DataSource = null;
            dgvMain.DataSource = _taskInfos;
            Task.Factory.StartNew(() => _dataPersistence.Save(Name + "_TaskList", _taskInfos));
        }

        private void OpenUrl(Func<TaskInfo, string> getUrl, bool isLocal = false)
        {
            foreach (var taskInfo in GetSelectList())
            {
                /*                if (isLocal)
                                {
                                    var form = new BrowserDialog(taskInfo.Keyword + " - " + taskInfo.Topic, getUrl(taskInfo));
                                    form.Show();
                                }
                                else*/
                Process.Start(getUrl(taskInfo));
            }
        }

        #endregion Private Method
    }
}